import axios from 'axios'
import { ElMessage } from 'element-plus';
import useStore from '@/stores'
import { storeToRefs } from 'pinia'
import router from '@/router';
const { userStore, routerStore } = useStore()



const instance = axios.create({
  // baseURL: 'http://139.199.194.207:8086/lanlu',//api地址
  baseURL: 'http://lanlu.free.idcfengye.com',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json;charset=utf-8',
  }
});

//请求拦截器
instance.interceptors.request.use(
  (config) => {
    //用户信息仓库
    const { getToken: token } = storeToRefs(userStore)

    // console.log('%c [token  ]-25', 'font-size:13px; background:pink; color:#bf2c9f;', token.value)
    if (token.value) {
      config.headers['token'] = token.value
    }
    return config
  },
  (error) => {
    console.log('%c [ request.js interceptors ]-27', 'font-size:13px; background:pink; color:#bf2c9f;', error)
    return Promise.reject(error)
  }
)


//响应拦截器
instance.interceptors.response.use(
  async (response) => {
    const { code, msg } = response.data

    if (code + '' === '401') { //token 失效

      const currentRoute = router.currentRoute.value.path

      console.log('%c [  ]-47', 'font-size:13px; background:pink; color:#bf2c9f;', currentRoute)
      if (currentRoute === '/login' || currentRoute === '/') return '已在登录'

      console.log('%c [  ]-48', 'font-size:13px; background:pink; color:#bf2c9f;', 112)
      try {
        await ElMessageBox.confirm('当前页面已失效，请重新登录', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        // 清除本地缓存
        userStore.removeToken()
        userStore.removeToken()
        routerStore.removeLocalStorageVisitedViews()
        // 跳转登录页
        router.push('/login')
      } catch (error) {
        console.log('%c [ request-登录失效 ]-56', 'font-size:13px; background:pink; color:#bf2c9f;', error)
      }
      return '请重新登录'
    } else if (code + '' !== '500') {
      return response.data
    } else if (code + '' === '403') {
      ElMessage.error('无权限访问')
      return '无权限访问！'
    }

    ElMessage.error(msg || '系统出错')
    return Promise.reject(msg)
  },
  async (error) => {
    console.log('%c [request.js   interceptors ]-41', 'font-size:13px; background:pink; color:#bf2c9f;', error)
    ElMessage.error(`${error.code}  ${error.message}`)
    if (error.response.data) {
      const { code, msg } = error.response.data
      ElMessage.error(msg || '系统出错')
    }



    return Promise.reject(error.message)
  }
)


// 导出axios实例
export default instance